package com.example.demo.interceptor;

import com.example.demo.properties.JwtProperties;
import com.example.demo.utils.BaseContext;
import com.example.demo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class LoginInterruption implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

       //获取请求头
        String header = request.getHeader(jwtProperties.getAdminTokenName());
         log.info("拦截器参数"+header);
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), header);
            Long id = Long.valueOf(claims.get("id").toString());
            BaseContext.setCurrentId(id);
            log.info("用户id{}",id);
            return true;
        }catch (Exception e){
         response.setStatus(401);
         return false;
        }
    }
}
